<template>
  <view class="work-page">
    <uni-table border stripe emptyText="暂无更多数据" width="100%">
      <!-- 表头行 -->
      <uni-tr width="100%">
        <uni-th align="center" v-for="i in offlineTitle.length" :key="i">{{
          offlineTitle[i - 1]
        }}</uni-th>
      </uni-tr>
      <!-- 表格数据行 -->
      <uni-tr v-for="(item, index) in offlineData" :key="index">
        <uni-td align="center" width="100">
          <!-- v-model="item.data" -->
          <!-- :value="item.data" -->
          <!-- @input="
              (e) => {
                item.data = Number(e.detail.value).toFixed(3)
                item.workdate = dateShow()[0]
                haveDataCheck()
              }
            "
            @blur="
              (e) => {
                item.data = Number(e.detail.value).toFixed(3)
              }
            " -->
          <input
            v-model="item.data"
            inputmode="none"
            placeholder="采集数据"
            :focus="currentFocus === index"
            :selection-start="0"
            :selection-end="10000"
            @focus="inputFocus(index)"
            @confirm="currentFocus++"
          />
        </uni-td>
        <uni-td align="center" v-for="j in offlineTitle.length - 2" :key="j">{{
          item[offlineTitle[j]]
        }}</uni-td>
        <uni-td align="center">{{ item.workdate }} </uni-td>
      </uni-tr>
    </uni-table>
    <button class="saveFile" @click="onClick" v-if="haveData">导出</button>
  </view>
</template>

<script setup>
import { useOfflineStore, useWorktoolStore } from '@/stores'
import { ref, onMounted, onUnmounted } from 'vue'
import { dateShow } from '@/utils/utils.js'
import { emitter } from '@/EventBus'
import * as XLSX from 'xlsx'
const offlineStore = useOfflineStore()
const worktoolStore = useWorktoolStore()
const offlineData = ref([])
const offlineTitle = ref([])
const currentFocus = ref(-1)
const haveData = ref(false)
// const deviceId = ref({})
// deviceId.value = worktoolStore.deviceId
function inputFocus(index) {
  //实际在@confirm已经将currentFocus++了，（confirm事件会自动将index++,并且马上进入@focus事件）
  currentFocus.value = index
  // console.log('currentFocus', [currentFocus.value, offlineData.value[currentFocus.value]])
}
function haveDataCheck() {
  haveData.value = offlineData.value.some((ele) => ele.data !== '')
  // haveData.value = true
}
function generateExcel(data, headers) {
  // 创建工作簿
  let worksheetData
  const wb = XLSX.utils.book_new()

  // 如果有自定义表头
  let worksheet
  if (headers) {
    // 添加表头行
    worksheetData = [headers, ...data]
    worksheet = XLSX.utils.aoa_to_sheet(worksheetData)
  } else {
    worksheet = XLSX.utils.json_to_sheet(data)
  }
  // console.log(worksheetData)

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(wb, worksheet, 'Sheet1')

  // 生成Excel文件
  const excelBuffer = XLSX.write(wb, {
    bookType: 'xlsx',
    type: 'array',
  })
  //生成base64 文件
  const base64Str = XLSX.write(wb, {
    bookType: 'xlsx',
    type: 'base64',
  })

  let blob = {}
  //#ifdef MP-WEIXIN
  blob = excelBuffer
  //#endif
  //#ifdef H5
  blob = new Blob([excelBuffer], {
    type: 'application/octet-stream',
    // type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  })
  console.log(blob)
  //#endif
  //#ifdef APP-PLUS
  //安卓系统不能下载blob文件(后续是通过excelbuffer转换成blob)所以要改成base64
  // blob = excelBuffer
  blob = base64Str
  //#endif
  return blob
}

function onClick() {
  //   [
  //     {
  //         "data": "0.520",
  //         "备注": "按范围要求",
  //         "最大值": 21,
  //         "最小值": 20,
  //         "内容": "aa",
  //         "工位": "P1",
  //         "workdate": "2025-04-21 20:10:38"
  //     },
  //     {
  //         "data": "1.940",
  //         "备注": "按范围要求",
  //         "最大值": 31,
  //         "最小值": 30,
  //         "内容": "bb",
  //         "工位": "P2",
  //         "workdate": "2025-04-21 20:10:40"
  //     },
  //     {
  //         "data": "4.230",
  //         "备注": "按范围要求",
  //         "最大值": 11,
  //         "最小值": 10,
  //         "内容": "cc ",
  //         "工位": "P3",
  //         "workdate": "2025-04-21 20:10:42"
  //     }
  // ]
  // console.log(offlineTitle.value)
  // ["数据","备注","最大值","最小值","内容","工位","操作时间"]
  const headers = offlineTitle.value
  //  [["数据","备注","最大值","最小值","内容","工位","操作时间"]]
  const data = []
  for (let v of offlineData.value) {
    data.push(Object.values(v))
  }
  const blob = generateExcel(data, headers)
  //#ifdef MP-WEIXIN
  saveExcelInWeixin(blob, 'data.xlsx')
  //#endif
  //#ifdef H5
  saveExcelInH5(blob, 'data.xlsx')
  haveData.value = false
  uni.navigateTo({ url: '/pages/login/login' })
  //#endif
  //#ifdef APP-PLUS
  saveExcelInApp(blob, 'data.xlsx', function (path) {
    console.log('result', path)
    // file:///storage/emulated/0/Android/data/io.dcloud.HBuilder/apps/HBuilder/doc/data.xlsx
    plus.runtime.openFile(path) //用第三方程序打开文件
    uni.navigateTo({ url: '/pages/login/login' })
  })
  //#endif
}
/*
 * APP保存Excel文件
 * @param {Blob} blob - Excel文件的excelBuffer对象
 * @param {String} fileName - 文件名（带后缀）
 * @param callback - 回调函数，返回path
 */
function saveExcelInApp(xlsxData, fileName, callback) {
  //下面是当xlsxData是excelbuffer时，需要转成base64
  // const base64Str = btoa(String.fromCharCode.apply(null, new Uint8Array(xlsxData)))

  //传过来的xlsxData已经是base64格式的，不需要再转了
  const base64Str = xlsxData
  // console.log('Base64:', base64Str)

  plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function (fs) {
    fs.root.getFile(fileName, { create: true }, function (entry) {
      // 获得本地路径URL，file:///xxx/doc/1663062980631.xlsx
      var fullPath = entry.fullPath

      let platform = uni.getSystemInfoSync().platform
      if (platform == 'android') {
        var Base64 = plus.android.importClass('android.util.Base64')
        var FileOutputStream = plus.android.importClass('java.io.FileOutputStream')
        try {
          var out = new FileOutputStream(fullPath)
          // 此处Base64.decode有长度限制，如果不能满足需求，可以考虑换成官方原生插件市场的【Base64转文件】
          var bytes = Base64.decode(base64Str, Base64.DEFAULT)
          out.write(bytes)
          out.close()
          // 回调
          callback && callback(entry.toLocalURL())
        } catch (e) {
          console.log(e.message)
        }
      } else if (platform == 'ios') {
        var NSData = plus.ios.importClass('NSData')
        var nsData = new NSData()
        nsData = nsData.initWithBase64EncodedStringoptions(base64Str, 0)
        if (nsData) {
          nsData.plusCallMethod({ writeToFile: fullPath, atomically: true })
          plus.ios.deleteObject(nsData)
        }
        // 回调
        callback && callback(entry.toLocalURL())
      }
    })
  })
}
/*
 * 微信小程序保存Excel文件
 * @param {Blob} blob - Excel文件的excelBuffer对象
 * @param {String} fileName - 文件名（带后缀）
 */
function saveExcelInWeixin(blob, fileName) {
  const filePath = `${wx.env.USER_DATA_PATH}/${fileName}`
  const fs = wx.getFileSystemManager()
  fs.writeFileSync(filePath, blob, 'utf-8')

  wx.shareFileMessage({
    filePath,
    success: function (res) {
      console.log('分享成功')
    },
    fail(e) {
      console.log(e)
    },
  })
}
/*
 * H5端保存Excel文件
 * @param {Blob} blob - Excel文件的Blob对象
 * @param {String} fileName - 文件名（带后缀）
 */
function saveExcelInH5(blob, fileName) {
  // 创建下载链接
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = fileName

  // 触发点击下载
  document.body.appendChild(link)
  link.click()

  // 清理
  setTimeout(() => {
    document.body.removeChild(link)
    URL.revokeObjectURL(link.href)
  }, 100)

  return Promise.resolve()
}
onMounted(async () => {
  //接收WorkHead发出的事件
  // emitter.on('onClickBlue', onClickBlue)
  emitter.on('process', processBleData)
  emitter.on('onSendData', onSendData)
  let offline = offlineStore.records
  //获取xlsx文件的标题列表。最前面加上'数据'及最后加上'操作时间'
  offlineTitle.value = ['数据', ...Object.keys(offline[0]), '操作时间']
  console.log('keys', offlineTitle.value)
  //获取xlsx文件的内容列表。最前面加上'数据'及最后加上'操作时间'
  offlineData.value = offline.map((v) => {
    return { data: '', ...v, workdate: '' }
  })
})
// function onClickBlue(item) {
//   clickBlue(item, processBleData)
// }
function onSendData() {
  let currFocus = currentFocus.value
  // sendData(processBleData, currFocus, 'none')
  emitter.emit('sendData', [currFocus, 'none'])
}
//下面是采集数据后的处理，需要根据当前具体组件的内容重写
function processBleData(getValue) {
  // console.log(value)
  // console.log(currentFocus.value)
  // console.log(offlineData.value[currentFocus.value])
  let value = getValue[0]
  let unit = getValue[1]
  offlineData.value[currentFocus.value].data = value.toFixed(3)
  offlineData.value[currentFocus.value].workdate = dateShow()[0]
  haveDataCheck()
  currentFocus.value++
}
onUnmounted(() => {
  //关闭WorkHead所发出的事件
  // emitter.off('onClickBlue')
  emitter.off('process', processBleData)
  emitter.off('onSendData')
})
</script>

<style scoped lang="scss">
.work-page {
  .margin-top-bottom {
    margin: 10px;
  }
  .saveFile {
    margin-top: 20px;
    width: 100%;
    height: 40px;
    line-height: 40px;
    background-color: #007aff;
    color: #ffffff;
    border-radius: 15px;
  }
}
</style>
